import React, { useEffect, useState } from 'react';
import { Message, Input, Button, Form, Space, Radio, Select, Spin } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import classnames from 'classnames';
import CryptoJS from 'crypto-js';

import styles from './style.module.scss';

import WebsiteName from 'components/WebsiteName';
import Navigate from 'components/Navigate';
import Beian from 'components/Beian';

import service from 'service'
import { getLocalUserInfo } from 'utils/util';

const accountsRules = {
    site: [{ required: false, message: "" }],
    website: [{ required: true, message: "网址不可为空" }, { pattern: /^((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)$/, message: "请输入正确的网址" }],
    introduction: [{ required: false, message: "" }],
    account: [{ required: true, message: "账号不可为空" }],
    password: [{ required: false, message: "" }],
    associates: [{ required: false, message: "" }],
    nickname: [{ required: false, message: "" }],
    status: [{ required: false, message: "" }, { pattern: /[012]/, message: "状态参数错误" }],
    remark: [{ required: false, message: "" }],
    tags: [{ required: false, message: "" }], // 数组字符串
    secretKey: [{ required: false, message: "" }, { pattern: /^\d{6}$/, message: '请输入六位数字密钥' }]
}
const alias = {
    site: '网站名称',
    website: '网站地址',
    introduction: '网站简介',
    account: '注册账户',
    password: '密码',
    associates: '关联账户',
    nickname: '账户昵称',
    status: '账户状态',
    remark: '备注',
    tags: '标签', // 数组
    secretKey: '加密密钥', // 数组
}
// const [SITE, WEBSITE, INTRODUCTION, ACCOUNT, PASSWORD, ASSOCIATES, NICKNAME, STATUS, REMARK, TAGS] = Object.keys(accountsRules);
const initRecord = {
    site: '',
    website: '', // https://www.runoob.com/jsref/jsref-sort.html
    introduction: '',
    account: '',
    password: '',
    associates: '',
    nickname: '',
    status: '0',
    remark: '',
    tags: [],
    secretKey: '',
}
const inputStyle = {
    minHight: 36, borderRadius: 3
}
// 批量添加
const name = 'batchAddList';
let timer = null;
export default (props) => {
    // 取出存放在localStorage中的批量添加列表
    const storageList = localStorage.getItem(name);
    const batchAddList = storageList ? JSON.parse(storageList) : []; // 初始化时从localStorage中取出的batchAddList

    const [labels, setLabels] = useState([]); // 标签
    const [globalSecretKey, setGlobalLabels] = useState(''); // 全局的加密密钥
    const [loading, setLoading] = useState(false);

    const columns = [
        { field: 'site', style: { ...inputStyle, width: 150 }, },
        { field: 'website', style: { ...inputStyle, width: 200 }, },
        { field: 'introduction', style: { ...inputStyle, width: 150 }, },
        { field: 'account', style: { ...inputStyle, width: 120 } },
        {
            field: 'password', style: { ...inputStyle, width: 180 }, render(opt) {
                let { key, style } = opt;
                return <Input.Password placeholder={alias[key]} style={style} />
            }
        },
        {
            field: 'secretKey', style: { ...inputStyle, width: 120 }, render(opt) {
                let { key, style } = opt;
                return <Input.Password placeholder={alias[key]} style={style} />
            }
        },
        { field: 'associates', style: { ...inputStyle, width: 180 } },
        { field: 'nickname', style: { ...inputStyle, width: 120 } },
        {
            field: 'status', style: { ...inputStyle, width: 180 }, render(opt) {
                let { key, style } = opt;
                return <Radio.Group initialValues={'2'} style={style} className={styles.customRadio}>
                    <Radio value={'0'}>正常</Radio>
                    <Radio value={'1'}>停用</Radio>
                    <Radio value={'2'}>注销</Radio>
                </Radio.Group>
            }
        },
        {
            field: 'remark', style: { ...inputStyle, width: 160 }, render(opt) {
                let { key, style } = opt;
                return <Input placeholder={alias[key]} style={style} />
            }
        },
        {
            field: 'tags', style: { ...inputStyle, width: 180 }, render(opt) {
                let { style } = opt
                return (
                    <Select
                        placeholder="请选择"
                        style={style}
                        showSearch
                        mode="multiple"
                    >
                        {labels.map(item => (<Select.Option key={item.id} value={item.id}>{item.label}</Select.Option>))}
                    </Select>
                )
            }
        },
    ]
    function onFinish(values) {
        // console.log('Received values of form:', values);
        const user = getLocalUserInfo() || {};
        const { id: userId } = user || {}
        if (!userId) {
            return Message.error('错误! 未登录用户')
        }
        let params = values.formList.map(item => {
            let { password, secretKey, ...other } = item;
            let key = secretKey || globalSecretKey
            let secretPass = password;
            if (password && key) {
                secretPass = CryptoJS.AES.encrypt(password, key).toString();
            }
            let temp = {
                ...other,
                password: secretPass,
            }
            return temp
        });
        setLoading(true)
        service.account.addMultiple(params)
            .then(result => {
                if (result) {
                    Message.success('批量添加成功!')
                    localStorage.removeItem(name)
                }
            })
            .finally(() => {
                setLoading(false);
            })
    }
    function onValuesChange(changedValues, allValues) {
        // console.log('onValuesChange', changedValues, allValues)
        clearTimeout(timer);
        timer = setTimeout(() => {
            localStorage.setItem(name, JSON.stringify(allValues.formList));
        }, 500)
    }
    function goBack() {
        props.history.goBack();
    }
    function getLabels() {
        const user = getLocalUserInfo() || {};
        const { id: userId } = user || {}
        if (!userId) {
            return Message.error('错误! 未登录用户')
        }
        let params = { creatorId: userId }
        service.label.findAll(params).then(result => {
            setLabels(result);
        })
    }
    useEffect(() => {
        getLabels()
    }, [])
    return (
        <div className={styles.container}>
            <div className={classnames(styles.header, styles.bg)}>
                <div className={styles.headerContent}>
                    <div className={styles.title}>
                        <WebsiteName />
                        <Navigate />
                    </div>
                    <div className={styles.operation}>
                    </div>
                </div>
            </div>
            <div className={classnames(styles.content, styles.bg)}>
                <Spin spinning={loading}>
                    <div className={styles.bar}>
                        <Space align="baseline" size={8}>
                            <span className={styles.label}>加密密钥:</span>
                            <Input.Password placeholder={alias['secretKey']} className={styles.inputWidth} onChange={e => setGlobalLabels(e.target.value)} />
                            <span className={styles.hint}>* 数据批量添加时, 会使用加密密钥对密码进行加密, 优先使用数据中设置的加密密钥, 其次为公共加密密钥, 如均未设置密钥, 则不加密</span>
                        </Space>
                    </div>
                    <div className={styles.table}>
                        <>
                            <div className={styles.header}>
                                <Space className={styles.space} align="baseline" size={8}>
                                    {columns.map((item, index) => {
                                        let { field: key, render, style } = item;
                                        return (
                                            <span key={index} value={alias[key]} style={{ ...style }} className={styles.th} >{alias[key]}</span>
                                        )
                                    })}
                                </Space>
                            </div>
                        </>
                        <Form
                            name="dynamic_form_nest_item"
                            onFinish={onFinish}
                            onValuesChange={onValuesChange}
                            autoComplete="off"
                        >
                            <Form.List name="formList" initialValue={batchAddList}>
                                {(fields, { add, remove, move }, errors) => {
                                    return (
                                        <>
                                            {fields.map((item, index) => {
                                                let { key, name, fieldKey, ...restField } = item;
                                                return (
                                                    <Space key={key} className={styles.space} align="baseline" size={8}>
                                                        {
                                                            columns.map(item => {
                                                                let { field: key, render, style } = item;
                                                                return (
                                                                    <Form.Item
                                                                        {...restField}
                                                                        key={index + '' + key}
                                                                        name={[name, key]}
                                                                        fieldKey={[fieldKey, key]}
                                                                        rules={accountsRules[key]}
                                                                        className={styles.formItem}
                                                                    >
                                                                        {render ? render({ key, style, record: batchAddList[index], index }) : <Input placeholder={alias[key]} style={style || inputStyle} />}
                                                                    </Form.Item>
                                                                )
                                                            })
                                                        }
                                                        <span style={{ padding: 6 }}>
                                                            <MinusCircleOutlined onClick={() => remove(name)} />
                                                        </span>
                                                    </Space>
                                                )
                                            })}
                                            <Form.Item>
                                                <Button type="dashed" onClick={() => add(initRecord)} block icon={<PlusOutlined />} style={inputStyle}>新增一条</Button>
                                            </Form.Item>
                                        </>
                                    )
                                }}
                            </Form.List>
                            <Form.Item wrapperCol={{ span: 4, offset: 10 }}>
                                <Space size={8}>
                                    <Button type="primary" htmlType="submit" style={{ width: 150 }} loading={loading} disabled={loading}>确定</Button>
                                    <Button style={{ width: 150 }} disabled={loading} onClick={goBack}>取消</Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </div>
                </Spin>
            </div>
            <div className={classnames(styles.footer, styles.bg)}>
                <Beian />
            </div>
        </div >
    )
}